#include "udp_client.hpp"
#include"err.hpp"

using namespace std;

static void usage(string proc)
{
    cout<<"Usage\n\t"<<proc<<" serverIp serverPort"<<endl;
}

int main(int argc,char*argv[])
{
    if(argc!=3)
    {
        usage(argv[0]);
        exit(USAGE_ERR);
    }

    //提取服务器信息
    string serverIp=argv[1];
    uint16_t serverPort=atoi(argv[2]);

    //创建套接字
    int sock=socket(AF_INET,SOCK_DGRAM,0);
    if(sock<0)
    {
        cerr<<"create sock error,"<<strerror(errno)<<endl;
        exit(SOCKET_ERR);
    }
    std::cout << "create socket success: " << sock << std::endl;

    //客户端不需要自己bind
    struct sockaddr_in server;
    memset(&server,0,sizeof(server));
    server.sin_family=AF_INET;
    server.sin_addr.s_addr=inet_addr(serverIp.c_str());
    server.sin_port=htons(serverPort);

    while(true)
    {
        cout<<"please enter your message# ";
        string message;
        cin>>message;

        sendto(sock,message.c_str(),message.size(),0,(struct sockaddr*)&server,sizeof(server));

        char buffer[1024];//接收返回的数据
        struct sockaddr_in tmp;//发送方
        memset(&tmp,0,sizeof(tmp));
        socklen_t len=sizeof(tmp);

        int n=recvfrom(sock,buffer,sizeof(buffer)-1,0,(struct sockaddr*)&tmp,&len);
        if(n>0)
        {
            buffer[n]='\0';
            cout<<"server echo# "<<buffer<<endl;
        }

    }
    return 0;
}